package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.User;

@WebServlet(name = "AdminUserInfoControllerServlet", urlPatterns = "/Admin/AdminUserInfoControllerServlet")
public class AdminUserInfoControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -6835363436176617148L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			String userId = request.getParameter("userid");

			if (userId == null) {
				userId = request.getParameter("id");
			}

			String loginId = request.getUserPrincipal().getName();

			User user = User.get(loginId);

			/* If user is a site admin, let them see anything */

			if (user.isSiteAdmin()) {
				User checkUser = User.get(userId);
				request.setAttribute("boardid", 0);
				request.setAttribute("user", checkUser);
				request.setAttribute("siteAdmin", true);

				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/userinfo.jsp");
				dispatcher.forward(request, response);
				return;
			}

			/*
			 * If they're a board admin, they can only look at details on their
			 * own board
			 */

			int boardId = Integer.parseInt(request.getParameter("boardid"));

			if (!user.isBoardAdmin(boardId)) {
				return;
			}

			User checkUser = User.get(userId);

			request.setAttribute("user", checkUser);
			request.setAttribute("boardid", boardId);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/userinfo.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
